package com.mywork.service;

import com.mywork.dao.TStorageMapper;
import com.mywork.dao.Test2Mapper;
import com.mywork.dao.Test4Mapper;
import com.mywork.dao.TestMapper;
import com.mywork.entity.TStorage;
import com.mywork.entity.Test;
import com.mywork.entity.Test2;
import com.mywork.entity.Test4;
import com.mywork.util.JSONUtil;
import com.mywork.util.SpringUtil;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ProjectName: testdemo
 * @ClassName: com.mywork.service
 * @Author: lsx
 * @Date: 2023/02/14 19:57
 **/
@Service
public class StorageService {

    @Resource
    private TStorageMapper tStorageMapper;

    @Resource
    private TestMapper testMapper;

    @Resource
    private Test2Mapper test2Mapper;

    @Resource
    private StorageService storageService;

    @Resource
    private Test4Mapper test4Mapper;

    public String index() {

        List<TStorage> users = tStorageMapper.selectAll();
        return JSONUtil.toJsonString(users);

    }

    public void test() {
        TStorage storage = new TStorage();
        storage.setCommodityCode("123");
        storage.setCommodityName("123");
        storage.setCount(123);
        tStorageMapper.insert(storage);

        StorageService storageService = SpringUtil.getBean(StorageService.class);

        storageService.insertDataOne();

        try {
            storageService.insertDataTwo();
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println(1);


    }


    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void insertDataOne() {
        Test test = new Test();
        test.setName("test1");
        testMapper.insertSelective(test);

        Test2 test2 = new Test2();
        test2.setName("test3");
        test2Mapper.insertSelective(test2);


    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void insertDataTwo() {
        Test test = new Test();
        test.setName("test2");
        testMapper.insertSelective(test);

        int i = 1 / 0;
        Test2 test2 = new Test2();
        test2.setName("test4");
        test2Mapper.insertSelective(test2);

    }

    public String insertTest() {
        Test4 test4 = new Test4();
        test4.setName("lsx");
        try {
            test4Mapper.insertSelective(test4);
        } catch (DuplicateKeyException de) {
            System.out.println(1);
        } catch (Exception e) {
            if (e instanceof DuplicateKeyException) {
                System.out.println(1);
            }
        }
        return "";
    }
}
